﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace Marbles.Core.Controls
{
    [ToolboxData("<{0}:TwitterFeed runat=server></{0}:TwitterFeed>")]
    public class TwitterFeed : FeedViewer
    {

        public string Account { get { object obj = ViewState["account"]; return (obj == null) ? string.Empty : obj.ToString(); } set { ViewState["account"] = value; } }
        public override string Url { get { return string.Format("http://twitter.com/statuses/user_timeline/{0}.rss", Account); } }     

        protected override TableRow CreateItemRow(string title, string description, DateTime pubdate, string url)
        {
            TableRow row = new TableRow();
            TableCell cell = new TableCell();
            Regex r = new Regex("(?<user>" + Account + "): (?<subject>.*)");
            string username = string.Empty;
            string subject = string.Empty;

            if (r.IsMatch(title))
            {
                Match m = r.Match(title);
                username = m.Groups["user"].Value;
                subject = m.Groups["subject"].Value;
            }

            row.Cells.Add(cell);

            if (ItemTemplate == null)
            {
                cell.Text = Settings.Environment.TwitterFormat(subject);
                cell.ToolTip = pubdate.ToLongDateString() + " " + pubdate.ToShortTimeString();
            }
            else
            {
                cell.ToolTip = pubdate.ToLongDateString() + " " + pubdate.ToShortTimeString();
                FeedTemplateContainer container = new FeedTemplateContainer(this);
                ItemTemplate.InstantiateIn(container);
                cell.Controls.Add(container);
                Control Title = container.FindControl("Title");
                Control Description = container.FindControl("Description");

                if (Title != null)
                {
                    if (Title.GetType() == typeof(HyperLink))
                    {
                        ((HyperLink)Title).Text = Settings.Environment.TwitterFormat(subject);
                        ((HyperLink)Title).NavigateUrl = url;
                        ((HyperLink)Title).ToolTip = pubdate.ToShortDateString() + " " + pubdate.ToShortTimeString();
                    }

                    if (Title.GetType() == typeof(Label))
                    {
                        ((Label)Title).Text = Settings.Environment.TwitterFormat(subject);
                    }
                }

                if (Description != null)
                {
                    Description.Visible = false;
                }
            }

            return row;
        }

    }
}
